package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.homeworkmanagement.dto.ClassesAndStudentsAndSubmissionsAndAssignmentsDTO;
import com.example.homeworkmanagement.pojo.Attachments;
import com.example.homeworkmanagement.pojo.Submissions;
import com.example.homeworkmanagement.mapper.SubmissionsMapper;
import com.example.homeworkmanagement.service.AttachmentsService;
import com.example.homeworkmanagement.service.SubmissionsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.utils.DocxUtil;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class SubmissionsServiceImpl extends ServiceImpl<SubmissionsMapper, Submissions> implements SubmissionsService {
     @Autowired
     private AttachmentsService attachmentsService;

     @Autowired
     private SubmissionsMapper submissionsMapper;

    @Override
    public ResultVO<Submissions> saveOrUpdateSubmission(Integer assignmentId, String studentId, MultipartFile file) {
        try {
            // 参数校验
            if (assignmentId == null) {
                return ResultVO.fail("作业ID（assignmentId）不能为空");
            }
            if (studentId == null || studentId.trim().isEmpty()) {
                return ResultVO.fail("学生ID（studentId）不能为空");
            }
            if (file == null || file.isEmpty()) {
                return ResultVO.fail("提交作业附件不可为空");
            }

            // 校验文件类型
            String filename = file.getOriginalFilename();
            if (filename == null || !filename.toLowerCase().endsWith(".docx")) {
                return ResultVO.fail("仅支持上传扩展名为.docx的文件");
            }

            // 解析并保存附件
            Attachments attachment;
            try {
                attachment = DocxUtil.convertToAttachment(file);
                boolean saveSuccess = attachmentsService.save(attachment);
                if (!saveSuccess) {
                    return ResultVO.fail("附件保存失败，请检查数据库连接或权限");
                }
            } catch (IOException e) {
                return ResultVO.fail("文件解析失败，可能是文件损坏或非有效DOCX格式");
            }

            // 查找现有记录
            QueryWrapper<Submissions> query = new QueryWrapper<>();
            query.eq("assignment_id", assignmentId).eq("student_id", studentId.trim());
            Submissions submission = getOne(query);

            // 新增或更新逻辑
            if (submission == null) {
                // 新增提交
                submission = new Submissions();
                submission.setAssignmentId(assignmentId);
                submission.setStudentId(studentId);
                submission.setGrade(null);
                submission.setFeedback("未有评语");
                submission.setState("2");
                submission.setSubDate(new Date());
            } else {
                // 更新提交：删除旧附件
                Integer oldAttachmentId = submission.getAttachment();
                if (oldAttachmentId != null) {
                    attachmentsService.deleteAttachment(oldAttachmentId);
                }
            }

            // 设置新附件ID
            submission.setAttachment(attachment.getAttachment());

            // 执行保存或更新
            boolean success = submission.getSubmissionId() == null ? save(submission) : updateById(submission);
            return success ? ResultVO.success(submission.getSubmissionId() == null ? "作业提交成功" : "作业更新成功", submission) : ResultVO.fail("操作失败，请重试");
        } catch (Exception e) {
            return ResultVO.fail("操作异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Submissions> deleteSubmission(Integer assignmentId, String studentId) {
        try {
            //查找作声作业
            if (assignmentId == null || studentId == null || studentId.trim().isEmpty()) {
                return ResultVO.fail("作业ID和学生ID不能为空");
            }

            QueryWrapper<Submissions> query = new QueryWrapper<>();
            query.eq("assignment_id", assignmentId).eq("student_id", studentId.trim());

            Submissions submission = getOne(query);
            if (submission == null) {
                return ResultVO.fail("未找到作业提交记录");
            }

            // 删除作业提交的对应附件
            Integer attachment = submission.getAttachment();
            if(attachment!=null){
                attachmentsService.deleteAttachment(attachment);
            }
            boolean success = remove(query);
            return success ? ResultVO.success("作业提交记录删除成功", submission) : ResultVO.fail("删除失败");
        } catch (Exception e) {
            return ResultVO.fail("删除作业提交时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Submissions> updateSubmissionTea(Integer assignmentId, String studentId, String grade, String feedback) {
        try{
            //查找作业记录
            if (assignmentId == null || studentId == null || studentId.trim().isEmpty()) {
                return ResultVO.fail("作业ID和学生ID不能为空");
            }

            QueryWrapper<Submissions> query = new QueryWrapper<>();
            query.eq("assignment_id", assignmentId).eq("student_id", studentId.trim());

            Submissions submission = getOne(query);
            if (submission == null) {
                return ResultVO.fail("未找到作业提交记录");
            }
            //更新分数
            submission.setGrade(grade);
            if(feedback!=null && !feedback.trim().isEmpty()){
                submission.setFeedback(feedback);
            }
            submission.setState("3");
            boolean updateSuccess = this.updateById(submission);
            return updateSuccess ? ResultVO.success("作业批改成功", submission) : ResultVO.fail("作业批改失败，请重新提交");

        }catch (Exception e){
            return ResultVO.fail("作业批改时发生异常："+e.getMessage());
        }
    }

    @Override
    public ResultVO<ClassesAndStudentsAndSubmissionsAndAssignmentsDTO> getSubmission(Integer assignmentId, String studentId) {
        try {
            //查找作业记录
            if (assignmentId == null || studentId == null || studentId.trim().isEmpty()) {
                return ResultVO.fail("作业ID和学生ID不能为空");
            }
            List<ClassesAndStudentsAndSubmissionsAndAssignmentsDTO> list=submissionsMapper.selectClassStudentSubmissionList(null,assignmentId,studentId,null,null,null,null,null,null,null);
            // 获取一个转为实体类
            ClassesAndStudentsAndSubmissionsAndAssignmentsDTO dto = list.get(0);
            return ResultVO.success("查询成功",dto);
        }catch (Exception e){
            return ResultVO.fail("查询作业时发生异常"+e.getMessage());
        }
    }


    //根据学生班级id串以及作业id查询学生作业列表
    @Override
    public ResultVO<List<ClassesAndStudentsAndSubmissionsAndAssignmentsDTO>> getSubmissionList(String classIds, Integer assignmentId, int page, int size) {
        try {
            if (assignmentId == null) {
                return ResultVO.fail("作业ID（assignmentId）不能为空");
            }

            // 解析班级ID列表
            List<Integer> classIdList = Arrays.stream(classIds.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());

            // 存储所有查询结果的列表
            List<ClassesAndStudentsAndSubmissionsAndAssignmentsDTO> allResults = new ArrayList<>();

            // 遍历每个班级ID，查询对应班级的作业提交记录
            for (Integer classId : classIdList) {
                List<ClassesAndStudentsAndSubmissionsAndAssignmentsDTO> classResults =
                        submissionsMapper.selectClassStudentSubmissionList(null, assignmentId, null, null, String.valueOf(classId), null, null, null,null,null);

                // 将当前班级的查询结果添加到总列表中
                allResults.addAll(classResults);
            }

            // 应用分页逻辑
            int startIndex = (page - 1) * size;
            int endIndex = Math.min(startIndex + size, allResults.size());

            //获取列表总数
            int total = allResults.size();
            // 截取当前页的数据
            List<ClassesAndStudentsAndSubmissionsAndAssignmentsDTO> pageResults =
                    allResults.subList(startIndex, endIndex);

            return ResultVO.success("查询成功", pageResults,total);
        } catch (Exception e) {
            return ResultVO.fail("查询学生作业列表失败：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<String> isSubmission(Integer assignmentId, String studentId) {
        try {
            // 参数校验
            if (studentId == null || studentId.trim().isEmpty()) {
                return ResultVO.fail("学生ID（studentId）不能为空");
            }
            if (assignmentId == null) {
                return ResultVO.fail("作业ID（assignmentId）不能为空");
            }
            Submissions submissions = this.getOne(new QueryWrapper<Submissions>().eq("assignment_id", assignmentId).eq("student_id", studentId));
            if (submissions == null) {
                return ResultVO.success("待提交");
            }
            return ResultVO.success("已提交");
        } catch (Exception e) {
            return ResultVO.fail("查询时发生异常");
        }
    }
}
